package com.qst.action;

import com.qst.*;
import com.qst.entity.TestPersonnel;
import com.qst.entity.User;
import com.qst.service.impl.ServiceFactory;
import com.qst.service.TestPersonnelService;
import com.qst.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebServlet("/login.action")
public class LoginServlet extends BaseServlet {

    private UserService userService = ServiceFactory.getService(UserService.class);
    private TestPersonnelService testPersonnelService = ServiceFactory.getService(TestPersonnelService.class);

    @Override
    protected void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端传递的参数
        String login = RequestUtil.getString(req, "login");
        String password = RequestUtil.getString(req, "password");
        int menu = RequestUtil.getInt(req, "menu");

        try {
            User user = userService.login(login, password);
            //将当前用户对象存储到会话中，以便跨多个请求持续访问。键名为Constant.CURRENT_USER。
            req.getSession().setAttribute(Constant.CURRENT_USER, user);
            if (user.getType() == 4) {
                TestPersonnel stu = testPersonnelService.findById(user.getId());
                req.getSession().setAttribute(Constant.CURRENT_TESTPERSONNEL, stu);
            }
            if (menu == 0) {
                //menu来自login.jsp里的hidden字段
                WebUtil.redirect(req, resp, "/frame.jsp");
            } else {
                //菜单为数据库读取，受权限控制，作为高级任务实现
                WebUtil.redirect(req, resp, "/index.jsp");
            }
        } catch (ExamException ex) {
            System.out.println(ex.getMessage());
            addError(req,ex.getMessage());

            req.setAttribute("login", login);
            WebUtil.redirect(req, resp, "/login.jsp");
        }
    }
}
